<?php
declare(strict_types=1);

namespace App\Controller\Admin\V1\Common;

use App\Controller\Admin\AdminController;
use App\Model\Area;
use App\Repositories\AreaRepository;

class AreaController extends AdminController
{
    public function all()
    {
        $parent_id = $this->request->input('parent_id',0);
        $where=[
            'parent_id'=>[
                'field' => 'parent_id',
                'value' => $parent_id
            ]
        ];
        $return= AreaRepository::getInstance()->all(['id','name','parent_id'],$where);
        return $this->response->success($return);
    }

    public function select(){
        $result = Area::Select();
        return $this->response->success($result);
    }

    public function allData(){
        $where=[
        ];
        $return= AreaRepository::getInstance()->all(['id','name','parent_id'],$where);
        return $this->response->success($return);
    }

    public function detail()
    {
        $model = AreaRepository::getInstance()->getById($this->request->input('id'));
        return $this->response->success($model);
    }

    public function list()
    {
        $parent_id = $this->request->input('parent_id',0);
        $search = [
            ['field'=>'parent_id','value'=>$parent_id]
        ];
        $orderBy= [
            [
                'field' => 'id',
                'sort' => 'asc'
            ]
        ];
        $datas = AreaRepository::getInstance()->getList('*',$search,['limit'=>10000],$orderBy);
        foreach ($datas['result'] as $key=>$data){
            $count = Area::query()->where('parent_id',$data['parent_id'])->count('id');
            if($count){
                $datas['result'][$key]['children']=[];
            }
        }
        return $this->response->success($datas);
    }
}